package com.example.blogsystem.controller;

import com.example.blogsystem.constant.Constant;
import com.example.blogsystem.model.Blog;
import com.example.blogsystem.model.Result;
import com.example.blogsystem.service.BlogService;
import com.example.blogsystem.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/blog")
public class BlogController {

    @Autowired
    BlogService blogService;

    //获取所有的博客-博客列表
    @RequestMapping("/getAllBlog")
    public List<Blog> getAllBlog() {
        return blogService.getBlogList();
    }

    //获取文章详情-查看某一个文章
    @RequestMapping("/getBlogDetail")
    public Result<Blog> getBlogById(Integer blogId, HttpServletRequest request) {
        log.info("getBlogDetail接口,blogId:{}", blogId);
        return blogService.getBlogById(blogId, request);
    }

    //发布博客
    @RequestMapping("/publish")
    public Result<Boolean> publishBlog(String title, String content, HttpServletRequest request){
        Result<Boolean> result = new Result<>();
        if(!StringUtils.hasLength(title) || !StringUtils.hasLength(content)) {
            log.error("title 或 content 为空");
            return result.fail("title 或 content 为空");
        }
        //获取用户id
        //1. 获取token
        //2. 获取token中的userId
        String userToken = request.getHeader(Constant.USER_TOKEN);
        Integer userId = JwtUtil.getUserIdFromToken(userToken);
        if(userId == null) {
            return result.fail("token中的userId为空");
        }
        //封装一个Blog发送
        Blog blog = new Blog(title, content, userId);
        Integer ret = blogService.publishBlog(blog);
        if(ret < 1) {
            return result.fail("发布失败");
        }
        return result.success(true);
    }

    //删除博客
    @RequestMapping("/delete")
    public Result<Object> deleteBlog(Integer blogId) {
        return blogService.deleteBlogLogic(blogId);
    }


}
